{* $Id$ *}
{include_core file="admin/lib/header.html" title="商品展示"}
<style>
  #js_upFile{
    position: absolute;
    top:0px;
    z-index: 20001;
    opacity: 0;
  }
  .js_editDiscount input{
    width:40px;
  }
</style>

<div class="page-header border-bottom clearfix">
  <h2 class="left">商品管理<span>在这里对商品进行管理</span></h2>
  <a href="{AnUrl('goods/admin/add')}" class="btn btn-success btn-sm right"><i class="icon-add"></i>添加商品</a>
</div>
<div class="search-form js_advancedForm">
  <form action="{AnUrl('goods/admin')}" method="get" class="js_goodsSearchForm">
    <input type="hidden" name="status" value="{$status}">
    <p>
      <label for="" class="search-f-label">商品标题：</label>
      <input type="text" class="search-f-ipt1" name="search_filter[title]" value="{$search_filter.title}">
    </p>
    <p>
      <label for="" class="search-f-label">商品价格：</label>
      <input type="text" class="search-f-ipt1 search-f-ipt2" name="search_filter[start_price]" value="{$search_filter.start_price}">
      <span class="search-f-line"></span>
      <input type="text" class="search-f-ipt1 search-f-ipt2" name="search_filter[end_price]" value="{$search_filter.end_price}">
    </p>
    <p>
      <label for="" class="search-f-label">销量：</label>
      <input type="text" class="search-f-ipt1 search-f-ipt2" name="search_filter[start_sale]" value="{$search_filter.start_sale}">
      <span class="search-f-line"></span>
      <input type="text" class="search-f-ipt1 search-f-ipt2" name="search_filter[end_sale]" value="{$search_filter.end_sale}">
    </p>
    <p>
      <label for="" class="search-f-label">添加时间：</label>
      <input type="text" class="search-f-ipt1 search-f-ipt2" name="search_filter[start_date]" value="{$search_filter.start_date}" id="startDate">
      <span class="search-f-line"></span>
      <input type="text" class="search-f-ipt1 search-f-ipt2" name="search_filter[end_date]" value="{$search_filter.end_date}" id="stopDate">
    </p>
    <p><label for="" class="search-f-label"></label><button type="submit" class="btn btn-success btn-xs js_searchBtn">搜索</button></p>
  </form>
</div>
<!--start:列表-->
<div class="list-table-filters">
  <p>
    <span class="label label-info">按状态</span>
    <a href='{AnUrl("goods/admin?{URLTracker::parse("status=1&is_sale=1&stock=1")}")}' {if URLTracker::val('status') == 1 && URLTracker::val('is_sale') == 1 && URLTracker::val('stock') == 1} class="label label-primary" {else} class="label label-default" {/if}>在售商品</a>
    <a href='{AnUrl("goods/admin?{URLTracker::parse("status=1&is_sale=1&stock=2")}")}' {if URLTracker::val('status') == 1 && URLTracker::val('is_sale') == 1 && URLTracker::val('stock') == 2} class="label label-primary" {else} class="label label-default" {/if}>售罄商品</a>
    <a href='{AnUrl("goods/admin?{URLTracker::parse("status=1&is_sale=0&stock=3")}")}' {if URLTracker::val('status') == 1 && URLTracker::val('is_sale') == 0 && URLTracker::val('stock') == 3} class="label label-primary" {else} class="label label-default" {/if}>待售商品</a>
    <a href='{AnUrl("goods/admin?{URLTracker::parse("status=0&is_sale=0&stock=3")}")}' {if URLTracker::val('status') == 0} class="label label-primary" {else} class="label label-default" {/if}>已删除</a>
  </p>
  <p>
    <span class="label label-info">按分类</span>
    <a href='{AnUrl("goods/admin?{URLTracker::set("category_id", 0)}")}' {if URLTracker::val('category_id') == 0} class="label label-primary" {else} class="label label-default" {/if}>全部</a>
    {foreach $category_list as $k => $v}
      <a href='{AnUrl("goods/admin?{URLTracker::set("category_id", $k)}")}' {if URLTracker::val('category_id') == $k} class="label label-primary" {else} class="label label-default" {/if}>{$v.title}</a>
    {/foreach}
  </p>
</div>
{include_core file="admin/lib/pager.html"}
<table class="list-table">
  <thead><tr>
    {if $status == 1}
    <th style="width:20px;"><input type="checkbox" class="selectAll"></th>
    {/if}
    <th>ID</th>
    <th style="width:60px;">封面</th>
    <th>商品信息</th>
    <th style="min-width:100px;">价格</th>
    <th style="min-width:100px;">二级差价</th>
    <th style="min-width:90px;">规格</th>
    <th style="min-width:80px;">创建时间</th>
    <th style="min-width:60px;">操作</th>
  </tr></thead>
  <tbody>
    {foreach $goods_list as $k=>$v}
    {if $v.cover}
    {$cover = _uri('attachment', (int)$v.cover, 'path')}
    {$image = _image($cover, small)}
    {/if}
      <tr id="dataList{$v.id}" data-id="{$v.id}" data-price="{$v.price}" data-cover="{$image}" data-title="{$v.title}" {if $k%2 == 1} class="bg-gray"{/if} data-id="{$v.id}" data-relation_ids="{goods_helper::get_goods_relation_ids($v.id)}">
        {if $status == 1}
        <td><input type="checkbox" class="listSelect"></td>
        {/if}
        <td>
          {$v.id}
        </td>
        <td>
          <img width="70" src="{$image}">
        </td>
        <td>
          <span class="label label-default">{$v.title}</span><br />
          分类：{$v.category_name}<br />
          简介：{$v.intro}
        </td>
        <td style="text-align: right">
          <span class="label label-default">出厂价 {num_keep_two_round($v.price)}</span><br/>
          {if $v.bbcoin == 0}
          <span class="label label-warning">抱币不可兑</span><br/>
          {else}
          <span class="label label-info">抱币兑 {$v.bbcoin}</span><br/>
          {/if}
          <span class="label label-default">终端进 {num_keep_two_round($v.market_price)}</span><br/>
        </td>
        <td style="text-align: right">
          <span class="label label-default">出厂价 +{num_keep_two_round($v.diff_price)}</span><br/>
          {if $v.bbcoin > 0}
          <span class="label label-info">抱币兑 +{$v.diff_bbcoin}</span><br/>
          {/if}
        </td>
        <td style="text-align: right">
          {$v.cube} m³<br/>
          {$v.weight} kg
        </td>
        <td>{$v.add_time}</td>
        <td>
          {if $status == 1}
            {* <span style="display:none;" id="js_text_{$v.id}">{$smarty.const.SITE_URL}/{$module}/{$v.id}.html</span>
            <a href="javascript:void(0);" class="btn btn-success btn-xs js_copyList" id="js_copy_{$v.id}" data-clipboard-target="js_text_{$v.id}">复制链接</a><br /> *}
            <a href="{AnUrl("goods/admin/add?id={$v.id}")}" class="btn btn-info btn-xs"><i class="icon-edit icon-white"></i>编辑商品</a><br />
            {if $is_sale == 0}
            <a href='{AnUrl("goods/admin/change_sale?id={$v.id}&is_sale=1")}' class="btn btn-primary btn-xs changeStatus" target="_blank">上架商品</a>
            <!-- <a href="{AnUrl("goods/admin/delete?id={$v.id}")}" class="btn btn-danger btn-xs deleteOne"><i class="icon-trash icon-white"></i>删除商品</a> -->
            {else}
            <a href='{AnUrl("goods/admin/change_sale?id={$v.id}&is_sale=0")}' class="btn btn-danger btn-xs changeStatus" target="_blank">下架商品</a>
            {/if}
          {elseif $status == 0}
            <a href="{AnUrl("goods/admin/change_status?status=1")}" class="btn btn-success btn-xs changeStatus"><i class="icon-trash icon-white"></i>恢复商品</a>
          {/if}

          {if $v.is_init}
              <!--  <a href='{AnUrl("goods/admin/change_init?id={$v.id}&is_init=1")}' class="btn btn-primary btn-xs changeStatus" target="_blank">允许盘点</a>  -->
          {else}
               <!--  <a href='{AnUrl("goods/admin/change_init?id={$v.id}&is_init=0")}' class="btn btn-danger btn-xs changeStatus" target="_blank">禁止盘点</a>  -->
          {/if}
        </td>
      </tr>
    {foreachelse}
        <tr><td class="txtleft" colspan="11">暂无数据</td></tr>
    {/foreach}
  </tbody>
  {if $status == 1}
  <tfoot>
    {if $is_sale == 1}
    <tr><td><input type="checkbox" class="selectAll"></td><td colspan="9"><a href="{AnUrl("goods/admin/change_sale")}" class="btn btn-danger btn-xs deleteAll">批量下架</a></td></tr>
    {else}
    <tr>
      <td><input type="checkbox" class="selectAll"></td><td colspan="9"><a href="{AnUrl("goods/admin/change_sale")}" class="btn btn-primary btn-xs deleteAll">批量上架</a>&nbsp;&nbsp;&nbsp;&nbsp;
      <a href="{AnUrl("goods/admin/delete")}" class="btn btn-danger btn-xs deleteAll">批量删除</a></td>
    </tr>
    {/if}
  </tfoot>
  {/if}
</table>
<div class="float-confirm js_discountDiv" style="z-index: 100;margin-left: 0px; margin-top: 0px; display: none; width:auto;">
  <div class="float-confirm-con">
    <p style="font-size:18px;color:#23a18b;">商品关联管理</p>
    <div style="width:auto;height:1px;background:#CCC;margin-bottom:20px;"></div>
    <div style="width:650px;height:auto;margin-bottom:15px;">
      <div class="js_mainGoods" style="width:600px;clear: both; padding-bottom: 10px; height: 40px; border-bottom:1px solid #EAEAEA;">
        <div style="float: left; margin-right: 20px; width: 40px; height: 40px;"></div>
        <div></div>
      </div>
      <a id="js_addRalation" class="btn btn-success btn-sm" href="javascript:void(0);" style="margin:10px 0px;">添加关联商品</a>
      <table class="list-table js_realtionGoods" style="width: 600px;"></table>
    </div>
    <div style="width:auto;height:1px;background:#CCC;margin-bottom:20px;"></div>
    <div class="float-confirm-btns">
      <a id="js_cancel" class="btn btn-default btn-sm" href="javascript:void(0);">取消</a>
    </div>
  </div>
</div>
<div class="float-bg" style="z-index: 99; display: none"></div>
<div class="js_showInfoDiv" style="display:none; z-index: 88; width:300px;height:auto; position: absolute; padding:20px;border:1px solid #ABABAB;background: #EFEFEF; border-radius: 4px;border-bottom: 2px solid #05A;">
  <div style="float: left;margin-right: 10px;"></div>
  <div style="white-space: nowrap; text-overflow: ellipsis; overflow: hidden; -o-text-overflow: ellipsis;"></div>
</div>
{include_core file="admin/lib/pager.html"}
<!--end:列表-->
<!--{load_js file='zclip/jquery.zclip.min.js'}-->
<!--{load_js file='zclip/ZeroClipboard.js'}-->
{load_js file='uploadify/jquery.uploadify.min.js'}
<script>
var resName = 'goods';
var jsCategoryId = "{$search_filter.category_id}";
$('.js_categoryId').load(siteUrl+'/category/load_category_option?res_name='+resName,function(){
  $('.js_categoryId').find('option').each(function(){
    if ($(this).attr('value') == jsCategoryId) {
      $(this).attr('selected','selected');
    }
  });
});
$(function(){

  $('.js_skuInfo').click(function(){
    var id = $(this).closest('tr').data('id');
    var html = '';
    $.ajax({
      type: "POST",
      url: siteUrl+"/goods/admin/get_sku_list",
      data: { id:id },
      async: false,
      cache: false,
      success: function(data){
        html = data;
      }
    })
    ace.dialog({
      title: 'SKU信息',
      content:html,
      ok:function(){
        qDialog.close()
      },
      cancel:function(){
        return true;
      }
    });
  })

  $('.js_gift').click(function(){
    var id = $(this).closest('tr').data('id');
    var html = '';
    $.ajax({
      type: "POST",
      url: siteUrl+"/goods/admin/get_gift_list",
      data: { id:id },
      dataType: "json",
      async: false,
      cache: false,
      success: function(data){
        if (data) {
          html += '<table class="list-table" data-id="'+id+'">';
          for (var i in data) {
            html += '<tr data-id="'+data[i]['id']+'"><td>'+data[i]['sku_info']+'</td><td>赠送数量：<em class="js_giftNum">'+ data[i]['gift_num'] +'</em></td><td width="100"><a href="javascript:void(0)" class="btn btn-success btn-xs js_giftEdit"><i class="icon-trash icon-white"></i>编辑</a> <a href="javascript:void(0)" class="btn btn-danger btn-xs js_giftDel">删除</a></td></tr>';
          }
          html += '<tr><td colspan="3"><a href="javascript:void(0)" class="btn btn-success btn-xs js_giftAdd"><i class="icon-trash icon-white"></i>新增赠品</a></td></tr></table>'
        } else {
          html += '<table class="list-table" data-id="'+id+'"><tr><td colspan="3"><a href="javascript:void(0)" class="btn btn-success btn-xs js_giftAdd"><i class="icon-trash icon-white"></i>新增赠品</a></td></tr></table>';
        }
      }
    })
    ace.dialog({
      title: '赠品管理',
      content:html,
      ok:function(){
        qDialog.close()
      },
      cancel:function(){
        return true;
      }
    });
  })

  $('.js_giftAdd').live('click', function(){
    var thisBtn = $(this);
    var goodsId = thisBtn.closest('table').data('id');
    var html = '';
    $.ajax({
      type: "POST",
      url: siteUrl+"/goods/admin/get_add_gift_list",
      data: { goods_id:goodsId },
      dataType: "json",
      async: false,
      cache: false,
      success: function(data){
        if (data) {
          html += '<tr><td><select class="js_addGift">';
          for (var i in data) {
            html += '<option value="'+ data[i]['id'] +'">'+ data[i]['sku_info']+'</option>';
          }
          html += '</select></td><td>赠送数量：<input value="1" style="width:20px;"></td><td><a href="javascript:void(0)" class="btn btn-success btn-xs js_giftSave" style="margin-right:5px;"><i class="icon-trash icon-white"></i>添加</a></td></tr>';
        }
        thisBtn.closest('tr').before(html);
      }
    })
  })

  $('.js_giftSave').live('click', function(){
    var thisBtn = $(this);
    var goodsId = thisBtn.closest('table').data('id');
    var skuId   = thisBtn.closest('tr').find('.js_addGift option:selected').val();
    var num     = thisBtn.closest('td').prev().find('input').val();

    if (!goodsId) {
      showMsg('请选择要添加赠品的商品');
      return false;
    }
    if (!skuId) {
      showMsg('请选择要添加的赠品');
      return false;
    }
    if (!num) {
      showMsg('请填写要赠送的数量');
      return false;
    }
    $.ajax({
      type: "POST",
      url: siteUrl+"/goods/admin/gift_add",
      data: { goods_id:goodsId, gift_sku_id:skuId, num:num },
      dataType: "json",
      async: false,
      cache: false,
      success: function(data){
        if (data.info != 'ok') {
          showMsg(data.info);
          return false;
        } else {
          html = '<tr data-id="'+data.data['id']+'"><td>'+data.data['sku_info']+'</td><td>赠送数量：<em class="js_giftNum">'+ data.data['gift_num'] +'</em></td><td width="100"><a href="javascript:void(0)" class="btn btn-success btn-xs js_giftEdit"><i class="icon-trash icon-white"></i>编辑</a> <a href="javascript:void(0)" class="btn btn-danger btn-xs js_giftDel">删除</a></td></tr>';
          thisBtn.closest('tr').before(html);
          thisBtn.closest('tr').remove();
        }
      }
    })
  })

  $('.js_giftEdit').live('click', function(){
    var val = $(this).closest('td').prev().find('.js_giftNum').html();
    $(this).closest('td').html('<a href="javascript:void(0)" class="btn btn-success btn-xs js_giftRight" style="margin-right:5px;"><i class="icon-trash icon-white"></i>确认</a><a href="javascript:void(0)" class="btn btn-danger btn-xs js_giftCancel"><i class="icon-trash icon-white"></i>取消</a>').prev().html('赠送数量:<input style="width:20px;" value="'+val+'">');
  })

  $('.js_giftCancel').live('click', function(){
    var val = $(this).closest('td').prev().find('input').val();
    $(this).closest('td').html('<a href="javascript:void(0)" class="btn btn-success btn-xs js_giftEdit"><i class="icon-trash icon-white"></i>编辑</a> <a href="javascript:void(0)" class="btn btn-danger btn-xs js_giftDel">删除</a>').prev().html('赠送数量：<em class="js_giftNum">'+ val +'</em>');
  })

  $('.js_giftDel').live('click', function(){
    var thisBtn = $(this);
    var giftId = thisBtn.closest('tr').data('id');
    showConfirm('确认要删除么', 1, function(){
      $.ajax({
        type: "POST",
        url: siteUrl+"/goods/admin/gift_del",
        data: { gift_id:giftId },
        dataType: "json",
        async: false,
        cache: false,
        success: function(data){
          if (data) {
            thisBtn.closest('tr').remove();
          }
        }
      })
    })
  })

  $('.js_giftRight').live('click', function(){
    var thisBtn = $(this);
    var val = $(this).closest('td').prev().find('input').val();
    var giftId = thisBtn.closest('tr').data('id');

    if (!val) {
      showMsg('请填写要赠送的数量');
      return false;
    }

    $.ajax({
      type: "POST",
      url: siteUrl+"/goods/admin/gift_edit",
      data: { num:val, gift_id:giftId },
      dataType: "json",
      async: false,
      cache: false,
      success: function(data){
        if (data) {
          thisBtn.closest('td').html('<a href="javascript:void(0)" class="btn btn-success btn-xs js_giftEdit"><i class="icon-trash icon-white"></i>编辑</a> <a href="javascript:void(0)" class="btn btn-danger btn-xs js_giftDel">删除</a>').prev().html('赠送数量：<em class="js_giftNum">'+ val +'</em>')
        }
      }
    })
  })



  // 高级搜索
  $('.js_advanced').click(function(e){
    e.preventDefault();
    var thisObj = $(this);
    var outBox  = thisObj.closest('form');
    if (thisObj.hasClass('js_isOpen')) {
      thisObj.removeClass('js_isOpen open');
      outBox.find('input').show();
      outBox.find('button').show();
      $('.js_advancedForm').hide();
    } else {
      thisObj.addClass('js_isOpen open');
      outBox.find('input').hide();
      outBox.find('button').hide();
      $('.js_advancedForm').show();
    }
  });

  // 高级搜索时间验证
  $('.js_searchBtn').click(function(e){
    e.preventDefault();
    var thisObj   = $(this);
    var startDate = $.trim($('#startDate').val());
    var stopDate  = $.trim($('#stopDate').val());
    if (startDate > stopDate) {
      showMsg('结束时间应大于等于开始时间');
      return;
    }
    thisObj.closest('form').submit();
  });

  // 页面复制
//  var clip = new ZeroClipboard( $('.js_copyList'), {
//    moviePath: "../../../../js/zclip/ZeroClipboard.swf"
//  });
//  clip.on( 'complete', function(client, args) {
//    showMsg("复制成功，复制内容为："+ args.text, 1);
//  });

  // 图片上传
  $('.js_previewBtn').each(function(i){
    $(this).click(function(e){
      e.preventDefault();
      var thisObj = $(this);
      var resName = 'goods';
      var resId = thisObj.closest('tr').attr('data-id');

      showPreviewDialog(resName, resId);
    });
  });

  $('.js_discountDiv').on('click', '#js_cancel', function(){
    closeDiv();
  });

  $('.js_discountDiv').next().click(function(){
    closeDiv();
  });

  $('.js_sltGoods').click(function(){
    $('.js_realtionGoods').html('努力加载中...');
    var goods     = $(this).closest('tr')
    var goodsId   = goods.data('id');
    if (!goodsId) {
      showMsg('请选择需要操作的商品');
      return;
    }
    var title     = goods.data('title');
    var price     = goods.data('price');
    var cover     = goods.data('cover');
    var height    = $(window).height();
    var width     = $(window).width();
    var divHeight = $('.js_discountDiv').height();
    var divWidth  = $('.js_discountDiv').outerWidth();
    var top       = $(document).scrollTop()+(height - divHeight)/3;
    var left      = (width - divWidth)/2 - 200;
    top = top < 0 ? 0: top;
    left = left < 0 ? 0: left;
    $('.js_mainGoods').children().eq(0).html('<img src="'+cover+'" width="40">').next().html('商品标题：'+title+'<br>商品价格:'+price);
    $('.js_discountDiv').css({ position:'absolute', display:'block', top:top+"px", left:left+"px" });
    $('.js_discountDiv').next().css('display', 'block');
    $('#js_addRalation').attr('data-goods_id', goodsId);
    getRelationList(goodsId);
  });

  $('js_discountDiv').on('click', '.js_deleteRelation', function(e){
    e.preventDefault();
    var href   = $(this).data('href');
    var currTr = $(this).closest('tr');
    var currTbody = $(this).closest('tbody');
    showConfirm('确定要删除当前关联商品？', 1, function(){
      $.post(href, {  }, function(json){
        if (json.info == 'ok') {
          currTr.remove();
          if (currTbody.children('tr').length == 0) {
            $('.js_realtionGoods').html('当前商品还有没关联商品');
          }
        } else {
          showMsg(json.info);
        }
      }, 'json');
    });
  });

  $('.js_discountDiv').on('click', '.js_editRelation', function(){
    var currType     = $(this).data('type');
    var parentTr = $(this).closest('tr');
    if (currType == 'edit') {
      var discount = parseInt(parentTr.find('.js_editDiscount').html());
      parentTr.find('.js_editDiscount').html('<input type="text" value="'+discount+'">');
      $(this).html('保存').next().hide();
      $(this).data('type', 'save');
    } else {
      var discount  = parentTr.find('.js_editDiscount').children('input').val();
      var salePrice = parentTr.find('.js_editDiscount').data('sale_price');
      var id        = $(this).data('id');
      var url       = "{AnUrl('goods/admin/eidt_realtion_goods')}";
      $.post(url, { id:id, discount:discount, sale_price:salePrice }, function(json){
        if (json.info == 'ok') {
          showMsg('修改成功');
        } else {
          showMsg(json.info);
        }
      }, 'json');
      parentTr.find('.js_editDiscount').html(discount);
      $(this).html('编辑').next().show();
      $(this).data('type', 'edit');
    }

  });
  $('.js_discountDiv').on('keyup', '.js_editDiscount input', function(){
    var parentTr = $(this).closest('tr');
    var discount = $(this).val();
    var price    = parseFloat($(this).parent().data('price'));
    var salePrice = discountMath(price, discount);
    $(this).parent().data('sale_price', salePrice);
    parentTr.find('.js_salePrice').html(salePrice);
  });

  $('.js_discountDiv').on('click', '#js_addRalation', function(){
    var goodsId = $(this).data('goods_id');
    addRelationGoods(goodsId);
  });

  // 显示信息
  $('.js_showInfo').on('mouseenter keydown', function(e){
    var cover = $(this).data('cover');
    var title = $(this).data('title');
    var price = $(this).data('price');
    var discount = $(this).data('discount');
    var salePrice = $(this).data('sale_price');
    var goodsId = $(this).data('goods_id');

    $('.js_showInfoDiv').children('div').eq(0).html('<img src="'+cover+'" width="70">');
    $('.js_showInfoDiv').children('div').eq(1).html('商品ID：'+goodsId+'<br>商品标题：'+title+'<br>商品价格：￥'+price+''+'<br>商品折扣：'+discount+'折<br>优惠价格：￥'+salePrice);

    //获取鼠标的位置
    var baseW = $(this).width();
    var top  = $(this).offset().top;
    var left = $(this).offset().left;
    var divW = $('.js_showInfoDiv').width();
    var divH = $('.js_showInfoDiv').height();
    var divLeft = left - (divW-baseW)/2-210;
    var divTop  = top - 190;

    $('.js_showInfoDiv').css({ top:divTop+'px', left:divLeft+'px' }).show();
  });
  $('.js_showInfo').on('mouseleave', function(e){
    $('.js_showInfoDiv').hide();
  });
});
// 关闭弹窗
function closeDiv(){
  $('.js_discountDiv').next().css('display', 'none');
  $('.js_discountDiv').css('display', 'none');
  location.href = location.href;
}

var discountMath = function(price, num){
  var tmpNum = num;
  if (isNaN(tmpNum)) {
    tmpNum = 0;
  }
  if (tmpNum != 0) {
    tmpNum = Math.abs(tmpNum);
    var numLen = tmpNum.toString().length;
    var base   = '1';
    for (var i=0; i < numLen; i++) {
      base = base+'0';
    }
    var basic = parseInt(base);
    var discount = parseFloat(tmpNum / basic * parseFloat(price));
    return discount.toFixed(2);
  } else {
    return price.toFixed(2);
  }
}

var getRelationList = function(goodsId)
{
  var url = "{AnUrl('goods/admin/get_relation_list')}"
  $.get(url, { goods_id:goodsId }, function(json){
    if (json.info == 'ok') {
      $('.js_realtionGoods').html(json.data);
      var height    = $(window).height();
      var divHeight = $('.js_discountDiv').height();
      var top = $(document).scrollTop()+(height - divHeight)/3;
      top = top < 0 ? 0: top;
      $('.js_discountDiv').css({ top:top+'px' });
    } else {
      $('.js_realtionGoods').html(json.info);
    }
  }, 'json');
}

var addRelationGoods = function(goodsId) {
  Goods.option = {
    getDataUrl: "{AnUrl('goods/admin/get_goods_list')}?goods_id="+goodsId,
    sltGoods: 1,
    divTitle: '添加关联商品'
  };
  Goods.goodSelect(function (data) {
    var relationIds = getGoodsIds().join(',');
    var discountArr = getGoodsDiscount().join(',');
    var priceArr    = getDiscountPrice().join(',');

    if (!goodsId) {
      alert('请选择要添加关联的主商品');
      return false;
    }

    $.ajax({
      type: "POST",
      url: "{AnUrl('goods/admin/add_relation_goods')}",
      data: { goods_id: goodsId, relation_ids:relationIds, discount_arr:discountArr, price_arr:priceArr },
      dataType: "json",
      async: false,
      cache: false,
      success: function (data) {
        if (data.info != 'ok') {
          showMsg(data.info);
          return false;
        }
        showMsg('添加成功');
        getRelationList(goodsId);
      }
    })
  })
};

// 获取选中的商品ids
function getGoodsIds()
{
  var goodsIds = new Array();
  $('#js_sltRelationGoods').find('.js_goodsIds').each(function(){
    if ($(this).attr('checked') == 'checked') {
      var id = $(this).closest('.select-goods').data('id');
      if (!isNaN(id) && typeof id != 'undefind') {
        goodsIds.push(id);
      }
    }
  });

  return goodsIds;
}

// 获取商品折扣
function getGoodsDiscount()
{
  var goodsIds = getGoodsIds();
  var idsLen = goodsIds.length;
  var discountArr = new Array();
  for (var i = 0; i < idsLen; i++) {
    var id = goodsIds[i];
    var discount = $('#js_sltRelationGoods').find('.goodsSale'+id).val();
    discountArr[i] = discount;
  }

  return discountArr;
}

// 获取商品价格
function getDiscountPrice()
{
  var goodsIds = getGoodsIds();
  var idsLen = goodsIds.length;
  var priceArr = new Array();
  for (var i = 0; i < idsLen; i++) {
    var id = goodsIds[i];
    var price = $('#js_sltRelationGoods').find('.goodsPrice'+id).html();
    priceArr[i] = price;
  }

  return priceArr;
}
</script>
{include_core file="admin/lib/footer.html"}